<!-- components/transaction-chart.vue -->
<template>
  <view class="chart-container">
    <mpvue-echarts 
      :echarts="echarts" 
      :onInit="onInit"
      canvasId="transaction-chart"
      ref="chart"
    />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts/core'  
import { LineChart } from 'echarts/charts'  
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import mpvueEcharts from 'mpvue-echarts'

// 注册必要的组件
echarts.use([
  LineChart,
  GridComponent,
  TooltipComponent,
  CanvasRenderer
])

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  timeRange: {
    type: Array,
    default: () => []
  }
})

const echartsRef = ref(null)



const onInit = (canvas, width, height) => {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height
  })
  canvas.setChart(chart)
  
  const option = getChartOption()
  chart.setOption(option)
  
  echartsRef.value = chart
  return chart
}

const getChartOption = () => {
  return {
    backgroundColor: '#ffffff',
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a0}: {c0}元',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.timeRange,
      axisLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      name: '交易额(元)',
      nameTextStyle: {
        color: '#666',
        padding: [0, 0, 0, 40]
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#e0e0e0'
        }
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        color: '#666'
      }
    },
    series: [
      {
        name: '交易额',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#1890ff'
        },
        lineStyle: {
          width: 3,
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
            { offset: 1, color: 'rgba(24, 144, 255, 1)' }
          ])
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(24, 144, 255, 0.5)' },
            { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
          ])
        },
        data: props.data
      }
    ]
  }
}

// 当数据变化时更新图表
onMounted(() => {
  if (echartsRef.value) {
    echartsRef.value.setOption(getChartOption())
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400rpx;
}
</style>